<template>
	<view class="page-box pad-30">
		<!-- 更换地址 -->
		<view class="bg-white pad-40 radius30">
			<view class="color-646464 font-26">选择地址</view>
			<view class="betweenX centerXY mar-top-30" @click="hanldeEditAddress">
				<view class="color-text">
					<view class="font-32">
						{{addressInfo.province}}{{addressInfo.city}}{{addressInfo.region}}{{addressInfo.street}}{{addressInfo.detail}}
					</view>
					<view class="font-26 mar-top-20">联系电话: {{addressInfo.tel}}</view>
				</view>
				<view class="centerXY select shrink">
					<view class="font-26">选择</view>
					<up-icon color="#ABA9B4" name="arrow-right" size="13"></up-icon>
				</view>
			</view>
		</view>

		<view class="mar-top-30" v-for="(item,shopIndex) in shopList" :key="item.id">
			<!-- 上门时间 -->
			<view class="workerInfo pad-bottom-30 bg-white pad-40 radius30">
				<view class="betweenX centerXY mar-top-30" @click="hanldeDatetime(item)">
					<view class="font-30 color-text">上门时间
						<template v-if="item.worker.plan_begin_at  > 0">
							<text
								v-if="item.worker.work_time_mode == 1">{{timeFormat(item.worker.plan_begin_at, 'yyyy-mm-dd hh:00')}}</text>
							<text
								v-if="item.worker.work_time_mode == 2">{{timeFormat(item.worker.plan_begin_at, 'yyyy-mm-dd')}}</text>
						</template>
						<text v-else>请选择上门时间</text>
					</view>
					<up-datetime-picker :minDate="minDate" :maxDate="maxDate" ref="datetimePickerRef"
						:formatter="formatter" @confirm="hanldeConfirmDate($event,item)" @cancel="item.isTime = false"
						:show="item.isTime" step="01:00:00" v-model="item.worker.newDate" format="YYYY-MM-DD HH:mm"
						:mode="item.worker.dateMode">
					</up-datetime-picker>
					<view class="centerXY select">
						<view class="font-26">修改</view>
						<up-icon color="#ABA9B4" name="arrow-right" size="13"></up-icon>
					</view>
				</view>
				<!-- 工人信息 -->
				<!-- @click="hanldeWorkerEdit(item.id)" -->
				<view @click="hanldeAddWorker(item.worker.id)" class="centerY betweenX mar-top-30">
					<view class="centerY">
						<image class="avatar" :src="item.worker.avatar"></image>
						<view class="mar-left-20">
							<view class="font-26 color-text">{{item.worker.name}}</view>
						</view>
					</view>
					<view class="centerXY select">
						<view class="font-26">增加服务</view>
						<up-icon color="#ABA9B4" name="arrow-right" size="13"></up-icon>
					</view>
				</view>
				<view v-if="item.tips" class="mar-top-30 font-26 color-error">提示：{{item.tips}}</view>
			</view>
			<view class="bg-white radius30 mar-top-30">
				<view class="pad-bottom-30 pad-40 list-border" v-for="(work,woIndex) in item.work_info" :key="woIndex">
					<view v-if="work.tips" class="mar-top-30 font-26 color-error">提示：{{work.tips}}</view>
					<view class="font-32 mar-top-30 color-text">{{work.work_name}}</view>
					<view class="betweenX centerXY mar-top-30">
						<view class="font-30 color-text">服务价格</view>
						<view class="color-646464 font-30" v-if="work.order_price">
							￥{{work.order_price}}元
						</view>
					</view>
					<view class="betweenX centerXY mar-top-30">
						<view class="font-30 color-text">{{work.unit}}</view>
						<view class="color-646464 font-26">
							<up-number-box :min="work.min_buy_num" @change="handleChangeNum($event,shopIndex,woIndex)"
								v-model="work.buy_num" :step="work.buy_step"></up-number-box>
						</view>
					</view>
					<view v-if="work.isCoupon" class="betweenX centerXY mar-top-30"
						@click="hanldeCoupon(shopIndex,woIndex,work)">
						<view class="font-30 color-text">优惠券</view>
						<view class="centerXY select">
							<view class="couponType" v-if="work.user_coupon_id">{{work.couponInfo.name}}</view>
							<view v-else class="font-26 color-error">选择</view>
							<up-icon color="#ABA9B4" name="arrow-right" size="13"></up-icon>
						</view>
					</view>
					<view class="betweenX centerXY mar-top-30">
						<view class="font-30 color-text">实付价格</view>
						<view v-if="work.act_pay_amount" class="color-error font-30">￥{{work.act_pay_amount}}元</view>
					</view>

					<view class="betweenX centerXY mar-top-30" v-for="(amount,inx) in work.extraAmount" :key="inx">
						<view v-if="amount.title" class="font-30 color-text">{{amount.title}}</view>
						<view v-else>{{ util.textOfAmountType(amount.amount_type) }}</view>
						<view class="color-error font-30">￥{{amount.amount}}</view>
					</view>

					<view class="betweenX centerXY mar-top-30" v-for="qu in  work.questions" :key="qu.id">
						<template v-if="qu.answer != null">
							<view class="flex-w" v-if="qu.type == 'checkbox'">
								<up-checkbox-group v-model="qu.answer" placement="row" iconPlacement="right">
									<up-checkbox labelColor="#1D1D1D" :customStyle="{marginBottom: '8px'}"
										:label="qu.title" :name="qu.id" />
								</up-checkbox-group>
							</view>

							<template v-if="qu.type == 'radio'">
								<view class="font-30 flex-w">{{qu.title}}</view>
								<up-radio-group v-model="qu.answerVal" placement="row">
									<up-radio :customStyle="{marginLeft: '8px'}" v-for="(an,index) in qu.answer"
										:key="index" :label="an" :name="an">
									</up-radio>
								</up-radio-group>
							</template>
						</template>
					</view>
				</view>
			</view>
		</view>

		<!-- 按钮 -->
		<view class="betweenX button-bottom centerY">
			<view class="flex-w">
				<view class="font-36 color-error" v-if="total"><text class="font-24">￥</text>{{total}}元</view>
				<view class="font-24 yuanjia color-CCCCCC">原价￥{{total_amount}}元</view>
			</view>
			<view v-if="propsType == 'car'">
				<view @click="hanldeConfirmOrder" class="btn3 button-style">去支付</view>
			</view>
			<view v-if="propsType == 'shop'" class="centerY">
				<view @click="hanldeServiceCartSave" class="btn">加入购入车</view>
				<view @click="hanldeConfirmOrder" class="btn2 button-style">去支付</view>
			</view>
		</view>

		<!-- 地址弹窗工人弹窗  -->
		<up-popup v-if="isAddress" :show="isAddress" round="20" bgColor="#f4f5f9" closeable @close="isAddress =false">
			<view class="pad-30 font-36 color-text">选择地址</view>
			<addressList rightButtonText="确定" @hanldeNext="hanldeNext"></addressList>
		</up-popup>
		<up-popup v-if="isWorker" :show="isWorker" round="20" bgColor="#f4f5f9" closeable @close="isWorker = false">
			<view class="pad-30 font-36 color-text">选择工人</view>
			<workerList :isBack="false" @hanldeNext="hanldeGetWorker" :workerData="workerData">
			</workerList>
		</up-popup>

		<!-- 选择优惠券 -->
		<up-popup :show="isCoupon" round="20" bgColor="#f4f5f9" closeable @close="isCoupon = false">
			<view class="pad-30 font-36 color-text text-center">选择优惠券</view>
			<couponList @hanldeCancel="isCoupon = false" :userCouponId="couponId" @hanldeConfirm="handleCoupon">
			</couponList>
		</up-popup>

		<!-- 选择支付方式 -->
		<up-popup v-if="isPay" :show="isPay" round="20" bgColor="#f4f5f9" closeable @close="isPay = false">
			<view class="pad-30 font-36 color-text">选择支付方式</view>
			<pay-list :orderNos="orderNos"></pay-list>
		</up-popup>
	</view>

</template>

<script setup>
	// 引入decimal.js 保证显示不失真
	import Decimal from 'decimal.js';
	import util from '@/util/util.js'

	import {
		ref,
		defineProps,
		onMounted,
		nextTick
	} from 'vue';
	import {
		multiSkill,
		addressDetail,
		orderMultiCreate,
		serviceCartSave,
		orderPreview,
		pageListNearby,
		getUserCouponAll
	} from '@/api/index.js'

	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'
	import {
		timeFormat
	} from '@/uni_modules/uview-plus';
	const datetimePickerRef = ref(null);

	// 接收参数
	const props = defineProps({
		data: {
			type: String
		},
		type: {
			type: String
		}
	})

	const propsObj = ref(JSON.parse(props.data));

	const hanldeAddWorker = (id) => {
		let ids = [];
		shopList.value.forEach(item => {
			item.work_info.forEach(info => {
				ids.push(info.work_id);
			})
		})

		if (ids.length > 0) {
			uni.navigateTo({
				url: `/pages/worker/detail?worker_id=${id}&worker=${JSON.stringify(ids)}`
			})
		}
	}

	// 时间选择
	const minDate = Date.now() + (2 * 60 * 60 * 1000); // 开始时间默认2小时过后
	const currentDate = new Date(Date.now());
	// 添加 2 个月
	const maxDate = currentDate.setMonth(currentDate.getMonth() + 1);
	// 选择优惠券
	const handleCoupon = (data) => {
		if (data?.id != undefined) {
			shopList.value[shopIndex.value].work_info[woIndex.value].user_coupon_id = data.id;
			shopList.value[shopIndex.value].work_info[woIndex.value].couponInfo = data;
		} else {
			shopList.value[shopIndex.value].work_info[woIndex.value].user_coupon_id = "";
			shopList.value[shopIndex.value].work_info[woIndex.value].couponInfo = {};
		}
		setOrderPreview();
		isCoupon.value = false;
	}

	const formatter = (type, value) => {
		if (type === 'minute') {
			return `00`;
		}
		return value;
	};

	// car购物车 shop单个商品
	const propsType = ref(props.type);

	// 切换工人， 获取工人信息
	const hanldeGetWorker = (data, userInfo) => {
		const shopItme = shopList.value.find(i => i.id == workerId.value);
		shopItme.worker.name = userInfo.name;
		shopItme.worker.avatar = userInfo.avatar;
		shopItme.worker.id = userInfo.worker_id;
		isWorker.value = false;
		if (isWorker.value == false) {
			setOrderPreview();
		}
	}

	// 选着优惠券
	let isCoupon = ref(false);
	let shopIndex = ref(0);
	let woIndex = ref(0);
	let couponId = ref(0);
	let total_amount = ref('--')
	const hanldeCoupon = (index, work) => {
		shopIndex.value = index;
		couponId.value = shopList.value[index].work_info[work].user_coupon_id
		woIndex.value = work;
		isCoupon.value = true;
	}

	// 微信校验接口
	const setOrderPreview = () => {
		uni.showLoading({
			title: '加载中...',
		})
		orderPreview({
			from_page: propsType.value == 'car' ? 2 : 3,
			order_data: getDataInfo(shopList.value, 'shop'),
			user_address_id: uni.getStorageSync('addressId')
		}).then(res => {
			shopList.value.forEach((item, index) => {
				item.tips = '';
				item.work_info.forEach((workInfoItem, idx2) => {
					workInfoItem.tips = '';
				})
			})
			if (res.code == 200) {
				res.data.lists.forEach((info, idx) => {
					info.service_details.forEach((workItem, idx2) => {
						shopList.value[idx].work_info[idx2].act_pay_amount = workItem
							.act_pay_amount;
						shopList.value[idx].work_info[idx2].extraAmount = workItem
							?.extra_amount_detail || [];
					})
				})

				total.value = res.data.total_act_pay_amount;
				total_amount.value = res.data.total_amount;
				uni.hideLoading();
			} else {
				shopList.value.forEach((item, index) => {
					res.data.errors.forEach((info, inx) => {
						if (index === info.data?._idx) {
							if (info.data?._idx2 != undefined) {
								item.work_info.forEach((workInfoItem, idx2) => {
									if (idx2 == info.data?._idx2) {
										workInfoItem.tips = info.msg;
									}
								})
							} else {
								item.tips = info.msg;
							}
						}
					})

					item.work_info.forEach(info => {
						info.act_pay_amount = '--';
					})
				})
				total.value = '--'
				uni.hideLoading();
			}
		})
	}

	// 总支付价格
	const total = ref('--');


	// 调用价格计算
	let buyNumber = ref(1);
	const handleChangeNum = (e, shopIndex, woIndex) => {
		shopList.value[shopIndex].work_info[woIndex].buy_num = e.value;
		buyNumber.value = e.value;
		// 校验接口
		setOrderPreview();
	}

	// 加入购物车
	const hanldeServiceCartSave = () => {
		serviceCartSave({
			worker_id: propsObj.value[0].worker_id,
			work_id: propsObj.value[0].work_ids[0],
			num: buyNumber.value
		}).then(res => {
			if (res.code == 200) {
				uni.$u.toast(res.msg);
			}
		})
	}

	// 提交订单数据
	const isPay = ref(false);
	const orderNos = ref([]);
	const hanldeConfirmOrder = () => {
		// 提交
		orderMultiCreate({
			from_page: propsType.value == 'car' ? 2 : 3,
			order_data: getDataInfo(shopList.value, 'shop'),
			user_address_id: uni.getStorageSync('addressId')
		}).then(res => {
			if (res.code == 200) {
				isPay.value = true;
				orderNos.value = res.data.order_nos;
			} else if (res.code == 20042) {
				uni.$u.toast(res.msg);
			}
		})
	}

	// 处理数据
	const getDataInfo = (data, type) => {
		let postOrder = [];
		let priceArray = [];
		data.forEach(item => {
			let time = item.worker.work_time_mode == 1 ? timeFormat(item.worker.plan_begin_at,
					'yyyy-mm-dd hh:00') :
				timeFormat(item.worker.plan_begin_at, 'yyyy-mm-dd');
			let obj = {
				worker_id: item.worker.id,
				plan_begin_at: time,
				service_details: []
			}
			item.work_info.forEach(info => {
				let infObj = {
					work_id: info.work_id,
					user_coupon_id: info.user_coupon_id, // 优惠券id
					buy_num: info.buy_num,
					questions: []
				};

				infObj.questions = info.questions.map(i => {
					if (i.answer != null) {
						return {
							title: i.title,
							answer: i.answerVal
						}
					}
				});
				obj.service_details.push(infObj);

				// 价格数组
				priceArray.push({
					price: info.order_price,
					num: info.buy_num,
					time: info.spend_time
				})
			})
			postOrder.push(obj);
		});
		return type == 'shop' ? postOrder : priceArray;
	}

	// 选择时间
	const datetime = ref(false);
	const datetimeVal = ref(Date.now());
	const dateMode = ref("date");
	// 改变时间状态
	const hanldeDatetime = (item) => {
		item.isTime = true;
	}

	// 关闭时间选择
	const hanldeConfirmDate = (e, item) => {
		item.isTime = false;
		item.worker.plan_begin_at = e.value;
		setOrderPreview();
	}

	// 获取地址
	const getAddressDetail = () => {
		addressDetail({
			id: uni.getStorageSync('addressId')
		}).then(res => {
			addressInfo.value = res.data.info;
		})
	}

	// 修改地址
	const isAddress = ref(false);
	const isWorker = ref(false);
	const hanldeEditAddress = () => {
		isAddress.value = true;
	}

	// 打开选择工人弹窗
	const workerId = ref('');
	const workerData = ref([]);
	const hanldeWorkerEdit = (id) => {
		workerId.value = id;

		const params = {
			ps: 100,
			page: 1,
			lat: addressInfo.value.lat,
			lgt: addressInfo.value.lgt,
			num: 1,
			work_id: props.work_id
		}
		pageListNearby(params).then(res => {
			workerData.value = res.data.data;
			isWorker.value = true;
		});
	}

	// 获取地址详情
	const addressInfo = ref({});
	const hanldeNext = (data) => {
		uni.setStorageSync('addressId', data.id);
		getAddressDetail();
		setOrderPreview();
		isAddress.value = false;
		addressInfo.value = data;
	}

	// 获取详情数据
	const shopList = ref([]);
	const getMultiSkill = () => {
		multiSkill({
			params: propsObj.value
		}).then(res => {
			res.data.lists.forEach(item => {
				let worker = item.worker;

				// 默认日期加一天
				worker.plan_begin_at = '';
				worker.newDate = Date.now();
				item.tips = "";
				// 选择日期属性
				if (worker.work_time_mode == 1) {
					worker.dateMode = 'datetime';
				} else if (worker.work_time_mode == 2) {
					worker.dateMode = 'date';
				}

				worker.isTime = false;
				item.work_info.forEach(info => {
					info.buy_num = info.min_buy_num;
					info.act_pay_amount = '--';
					info.questions.forEach(qu => {
						qu.answerVal = "";
					})
				})
			})

			// 默认获取优惠券
			getUserCouponAll({
				use_status: 1
			}).then(coupon => {
				if (coupon.data.lists.length > 0) {
					res.data.lists.forEach(item => {
						item.work_info.forEach(info => {
							for (let i = 0; i < coupon.data.lists.length; i++) {
								let iCoupon = coupon.data.lists[i];
								let iCouponData = iCoupon.valid_scene_data;
								if (iCouponData.work_ids.includes(info.work_id)) {
									info.couponInfo = iCoupon;
									info.user_coupon_id = iCoupon.id;
									info.isCoupon = true;
									break;
								} else {
									info.isCoupon = false;
								};
							}
						})
					})
				}

				shopList.value = res.data.lists;
			})

		})
	}

	onLoad(() => {
		getMultiSkill();
	})

	// 接收参数
	onShow(() => {
		uni.$once('updateData', function(data) {
			propsObj.value.forEach(item => {
				if (data.worker_id == item.worker_id) {
					item.work_ids = data.work_ids;
				}
			})
			total.value = '--';
			getMultiSkill();
		})
		getAddressDetail();
	})
</script>

<style scoped lang="scss">
	.yuanjia {
		text-decoration: line-through;
	}

	.page-box {
		padding-bottom: 200rpx;
	}

	.workerInfo {
		border-bottom: 1rpx solid #F4F6F8;
		position: relative;
	}

	:deep(.u-radio-group) {
		flex: none;
	}

	.workerInfo::after {
		content: '';
		position: absolute;
		width: 20rpx;
		height: 50rpx;
		background: $uni-color-primary;
		left: 30rpx;
		bottom: -40rpx;
		z-index: -1;
	}

	.workerInfo::before {
		content: '';
		position: absolute;
		width: 20rpx;
		height: 50rpx;
		background: $uni-color-primary;
		bottom: -40rpx;
		right: 30rpx;
		z-index: -1;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.select {
		color: #ABA9B4;
	}

	:deep(.u-checkbox) {
		width: 100%;
	}


	.button-bottom {
		width: 100%;
		padding: 35rpx 40rpx;
		box-sizing: border-box;
		background: white;
		position: fixed;
		bottom: 0rpx;
		left: 0rpx;
		z-index: 2;
	}

	.btn {
		height: 100rpx;
		border-radius: 50rpx 0 0 50rpx;
		padding: 0 40rpx;
		line-height: 100rpx;
		background: rgba(0, 85, 254, 0.1);
		text-align: center;
		color: $uni-color-primary;
	}

	.btn2 {
		height: 100rpx;
		border-radius: 0 50rpx 50rpx 0;
		padding: 0 40rpx;
		line-height: 100rpx;
		text-align: center;
	}

	.btn3 {
		width: 220rpx;
		height: 100rpx;
		border-radius: 50rpx;
		padding: 0 40rpx;
		line-height: 100rpx;
		text-align: center;
	}

	.couponType {
		background: linear-gradient(270deg, #FF4913 0%, #FE9013 100%);
		padding: 8rpx 15rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
		color: white;
	}

	.list-border {
		border-bottom: 2rpx solid #F4F6F8;
	}
</style>